package com.sskjdata.cg.controller.sys.user;

import com.sskjdata.cg.controller.BaseController;
import com.sskjdata.cg.dto.ResponseCodeEnum;
import com.sskjdata.cg.dto.ResponseData;
import com.sskjdata.cg.jwt.JwtUser;
import com.sskjdata.cg.po.sys.SysUser;
import com.sskjdata.cg.service.auth.AuthService;
import com.sskjdata.cg.service.sys.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

/**
 * @Descirption 用户
 * @Author Jason
 * @Date 2018/6/14/
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private AuthService authService;
	@Autowired
	private AuthenticationManager authenticationManager;


    @GetMapping("/hello")
    public ResponseData welcome(){
        return new ResponseData(ResponseCodeEnum.SUCCESS);
    }

    /**
     * 提示去登录
     * @return
     */
    @GetMapping("/toLogin")
    public ResponseData toLogin(){
        return new ResponseData(ResponseCodeEnum.AUTH_LOGIN_IS_REQUIRED);
    }

    

    /**
     * 检查/修改密码
     * 
     * @return
     */
    @PostMapping("/checkPass")
    public ResponseData checkPass(@RequestParam(name="oldPass") String oldPass,
    		@RequestParam(name="newPass") String newPass) {
    	
    	String username = null;
    	JwtUser user 	= null;
    	try {
			user = getJwtUser();
			username = user.getUsername();
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseData(ResponseCodeEnum.AUTH_LOGIN_IS_REQUIRED);
		}
    	
    	// 校验用户是否合法
    	try {
			String token = authService.login(authenticationManager,username, oldPass);
			if(token!=null&&token.length()>0) { // 校验通过
				SysUser sysUser = new SysUser();
				sysUser.setPassword(newPass);
				sysUser.setId(Long.parseLong(user.getId()));
				
				SysUser updateUser = sysUserService.updatePass(sysUser);
					return new ResponseData(ResponseCodeEnum.SUCCESS,updateUser);
			}else{
				return new ResponseData(ResponseCodeEnum.UPDATE_PWD_ERROR);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return new ResponseData(ResponseCodeEnum.FAILURE);
    }


}
